package cn.xinjiu.reggie.controller;

import cn.xinjiu.reggie.common.R;
import cn.xinjiu.reggie.dto.DishDto;
import cn.xinjiu.reggie.entity.Category;
import cn.xinjiu.reggie.entity.Dish;
import cn.xinjiu.reggie.entity.DishFlavor;
import cn.xinjiu.reggie.service.CategoryService;
import cn.xinjiu.reggie.service.DishFlavorService;
import cn.xinjiu.reggie.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by xinchen on 2022/7/5
 *
 * @Description : 菜品
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * @param page     当前页数
     * @param pageSize 页面条数
     * @param name     查询条件
     * @return 分页对象
     * @description 分页
     */
    @RequestMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        log.info("/dish/page/ page={}, pageSize={}, name={}", page, pageSize, name);
        Page<Dish> pageInfo = new Page(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();
        // 添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        // 添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        // 分页
        dishService.page(pageInfo, lambdaQueryWrapper);

        // 对象拷贝 (被拷贝对象，目标对象，忽略属性)
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        // 将Dish集合中的每一个对象 拷贝到 DishDto集合的每一个对象
        List<DishDto> dishDtoList = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            // 拷贝除了分类名称的其他信息
            BeanUtils.copyProperties(item, dishDto);
            // 分类id
            Long categoryId = item.getCategoryId();
            // 根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            // 获取分类名称
            String categoryName = category.getName();
            // 给dishDto设置分类名称
            dishDto.setCategoryName(categoryName);
            return dishDto;
            // 重新转为集合
        }).collect(Collectors.toList());

        // 为dishDtoPage设置分页数据
        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    /**
     * @param dishDto
     * @return
     * @description TODO 新增菜品
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("/dish/ dishDto={}", dishDto);

        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }


    /**
     * @param id
     * @return
     * @description TODO 根据id查询菜品信息和对应的口味信息
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    /**
     * @param dishDto
     * @return
     * @description TODO 修改菜品
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("/dish/ dishDto={}", dishDto);

        dishService.updateWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * @param dish
     * @return
     * @description TODO 根据条件查询对应的菜品
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        // 添加过滤条件
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 只查询状态为在售（status = 1）
        queryWrapper.eq(Dish::getStatus, 1);
        // 添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

    /**
     * 修改一个/多个菜品的状态，没有算法，全是感情
     * @param status
     * @param ids
     * @return
     * @description TODO 更改菜品状态
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, Long[] ids) {

        for (int i = 0; i < ids.length; i++) {
            // Dish dish = dishService.getById(ids);
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, ids[i]);
            Dish dish = dishService.getOne(queryWrapper);
            // 修改菜品状态
            dish.setStatus(status);
            dishService.updateById(dish);
        }

        return R.success("更改菜品状态成功!");
    }


    /**
     * 删除一个/多个菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            log.info("delete dish : {}", ids);
//        categoryService.removeById(ids);
            dishService.removeById(ids[i]);
        }

        return R.success("分类信息删除成功");
    }


}